﻿using System;
using System.Diagnostics;
using System.Web;
using SecurityClient;
using System.Configuration;

namespace SecurityModule.Workflows
{
    class WFPostSetup : SimpleWorkflow
    {
        public WFPostSetup()
        {
            Verb = "POST";
            Path = "/Setup";
        }

        public override void PreProcessImplementation(HttpContext context)
        {
            // No pre-processing
        }

        public override void PostProcessImplementation(HttpContext context)
        {
            //Capture clientId from response.redirect
            if (context.Response.StatusCode != 302 || string.IsNullOrEmpty(context.Response.RedirectLocation)) return;

            var emailAddress = string.Empty;

            try
            {
                var url = new Uri(context.Response.RedirectLocation.ToAbsoluteUrl());
                var nvc = HttpUtility.ParseQueryString(url.Query);
                var clientCode = nvc["ClientCode"];
                emailAddress = context.Request.Form["Email"];

                //Store token
                var security = new SecurityServiceProxy();
                var result = security.RequestEmailVerification(clientCode, emailAddress);
                if (result.Success)
                {
                    var helper = new EmailHelper(GetEmailTemplatePath("EmailVerificationRequest"),
                                                 ConfigurationManager.AppSettings["RootUrl"],
                                                 ConfigurationManager.AppSettings["SupportEmail"],
                                                 ConfigurationManager.AppSettings["AppName"]
                        );
                    var emailBody = helper.GetEmailBody(new
                        {
                            token = result.TokenId,
                            path = "Setup/Verify",
                            workflow = "setting up your account at " + ConfigurationManager.AppSettings["AppName"]
                        });
                    try
                    {
                        // send invitation email
                        helper.SendEmail(emailAddress, "Email Verification", emailBody);
                    }
                    catch (Exception exp)
                    {
                        // sending email failed
                        EventLog.WriteEntry("SecModule",
                                            string.Format(
                                                "Failed sending email to reset Yubikey for user {0}, error: {1}",
                                                emailAddress,
                                                exp.Message), EventLogEntryType.Error);
                    }
                }
                else
                {
                    EventLog.WriteEntry("SecModule", string.Format("Failed acquiring setup token for user {0}", emailAddress), EventLogEntryType.Error);
                }
            }
            catch (Exception exp)
            {
                // preparing email failed
                EventLog.WriteEntry("SecModule", string.Format("Failed preparing email to reset Yubikey for user {0}, error: {1}", emailAddress, exp.Message), EventLogEntryType.Error);
            }
        }
    }
}
